const l = 42; // 滑块边长
const r = 10; // 滑块半径
const w = 310; // canvas宽度
const h = 155; // canvas高度
const PI = Math.PI;
const L = l + r * 2; // 滑块实际边长
// 1.获得随机数
function getRandomNumberByRange(start, end) {
  return Math.round(Math.random() * (end - start) + start);
}
// 2.创建canvas元素
function createCanvas(width, height) {
  const canvas = createElement("canvas");
  canvas.width = width;
  canvas.height = height;
  return canvas;
}
// 3.创建图片元素
function createImg(onload) {
  const img = createElement("img");
  img.crossOrigin = "Anonymous";
  img.onload = onload;
  img.onerror = () => {
    img.src = getRandomImg();
    // img.src = "31.jpg";;
  };
  img.src = getRandomImg();
  // img.src = "31.jpg";;
  return img;
}
// 4.创建元素
function createElement(tagName) {
  return document.createElement(tagName);
}
// 5.添加样式
function addClass(tag, className) {
  tag.classList.add(className);
}
// 6.移除样式
function removeClass(tag, className) {
  tag.classList.remove(className);
}
// 7.获取背景图片
function getRandomImg() {
  return (
    "https://picsum.photos/300/150/?image=" + getRandomNumberByRange(0, 100)
  );
}
// 8.画拼图块
// 参考：https://www.w3school.com.cn/tags/html_ref_canvas.asp
/*
 * ctx: canvas对象
 * operation:
 * x: x轴数据
 * y: y轴数据
 */
function draw(ctx, operation, x, y) {
  //绘制
  ctx.beginPath(); // 起始一条路径，或重置当前路径
  //left
  ctx.moveTo(x, y); // 把路径移动到画布中的指定点，不创建线条
  //top
  ctx.lineTo(x + l / 2, y); // 添加一个新点，然后在画布中创建从该点到最后指定点的线条
  ctx.arc(x + l / 2, y - r + 2, r, 0, 2 * PI); // 创建弧/曲线（用于创建圆形或部分圆）
  //right
  ctx.lineTo(x + l / 2, y);
  ctx.lineTo(x + l, y);
  ctx.lineTo(x + l, y + l / 2);
  ctx.arc(x + l + r - 2, y + l / 2, r, 0, 2 * PI);
  ctx.lineTo(x + l, y + l / 2);
  ctx.lineTo(x + l, y + l);
  ctx.lineTo(x, y + l);
  ctx.lineTo(x, y);
  //修饰，没有会看不出效果
  ctx.fillStyle = "#fff"; // 设置或返回用于填充绘画的颜色、渐变或模式
  ctx[operation]();
  ctx.beginPath();
  ctx.arc(x, y + l / 2, r, 1.5 * PI, 0.5 * PI);
  ctx.globalCompositeOperation = "xor"; // 设置或返回新图像如何绘制到已有的图像上
  ctx.fill(); // 填充当前绘图（路径）
}
// 9.求和
function sum(x, y) {
  return x + y;
}
// 10.求平方
function square(x) {
  return x * x;
}
// 11.创建类
class jigsaw {
  constructor(el, success, fail) {
    this.el = el;
    this.success = success;
    this.fail = fail;
  }
  init() {
    this.initDOM(); // 初始化dom
    this.initImg(); // 初始化背景画布
    this.draw(); // 初始化拼图块
    this.bindEvents(); // 绑定事件
  }
  initDOM() {
    // 创建canvas元素
    const canvas = createCanvas(w, h); // 画布
    const block = canvas.cloneNode(true); // 滑块
    const sliderContainer = createElement("div"); // 滑块容器
    const refreshIcon = createElement("div"); // 刷新按钮div
    const sliderMask = createElement("div"); // 滑块样式，滑块在验证正确，错误时样式的div
    const slider = createElement("div"); // 滑块div
    const sliderIcon = createElement("span"); // 滑块图标
    const text = createElement("span"); // 滑块提示内容
    block.className = "block";
    sliderContainer.className = "sliderContainer";
    refreshIcon.className = "refreshIcon";
    sliderMask.className = "sliderMask";
    slider.className = "slider";
    sliderIcon.className = "sliderIcon";
    text.innerHTML = "向右滑动滑块填充拼图";
    text.className = "sliderText";
    const el = this.el;
    el.appendChild(canvas);
    el.appendChild(refreshIcon);
    el.appendChild(block);
    slider.appendChild(sliderIcon);
    sliderMask.appendChild(slider);
    sliderContainer.appendChild(sliderMask);
    sliderContainer.appendChild(text);
    el.appendChild(sliderContainer);
    Object.assign(this, {
      canvas,
      block,
      sliderContainer,
      refreshIcon,
      slider,
      sliderMask,
      sliderIcon,
      text,
      canvasCtx: canvas.getContext("2d"),
      blockCtx: block.getContext("2d"),
    });
  }
  initImg() {
    // 创建图片元素
    const img = createImg(() => {
      this.canvasCtx.drawImage(img, 0, 0, w, h);
      this.blockCtx.drawImage(img, 0, 0, w, h);
      const y = this.y - r * 2 + 2;
      const ImageData = this.blockCtx.getImageData(this.x, y, L, L);
      this.block.width = L;
      this.blockCtx.putImageData(ImageData, 0, y);
    });
    this.img = img;
  }
  draw() {
    // 随机创建滑块的位置
    this.x = getRandomNumberByRange(L + 10, w - (L + 10));
    this.y = getRandomNumberByRange(10 + r * 2, h - (L + 10));
    draw(this.canvasCtx, "fill", this.x, this.y);
    draw(this.blockCtx, "clip", this.x, this.y);
  }
  clean() {
    // 清空上一次滑块的操作
    this.canvasCtx.clearRect(0, 0, w, h);
    this.blockCtx.clearRect(0, 0, w, h);
    this.block.width = w;
  }
  // 绑定事件
  bindEvents() {
    this.el.onselectstart = () => false;
    this.refreshIcon.onclick = () => {
      this.reset();
    };
    let originX,
      originY,
      trail = [],
      isMouseDown = false;
    this.slider.addEventListener("mousedown", (e) => {
      (originX = e.x), (originY = e.y);
      isMouseDown = true;
    });
    document.addEventListener("mousemove", (e) => {
      if (!isMouseDown) return false;
      const moveX = e.x - originX;
      const moveY = e.y - originY;
      if (moveX < 0 || moveX + 38 >= w) return false;
      this.slider.style.left = moveX + "px";
      var blockLeft = ((w - 40 - 20) / (w - 40)) * moveX;
      this.block.style.left = blockLeft + "px";
      addClass(this.sliderContainer, "sliderContainer_active");
      this.sliderMask.style.width = moveX + "px";
      trail.push(moveY);
    });
    document.addEventListener("mouseup", (e) => {
      if (!isMouseDown) return false;
      isMouseDown = false;
      if (e.x == originX) return false;
      removeClass(this.sliderContainer, "sliderContainer_active");
      this.trail = trail;
      const {
        spliced,
        TuringTest
      } = this.verify();
      if (spliced) {
        if (TuringTest) {
          addClass(this.sliderContainer, "sliderContainer_success");
          this.success && this.success();
        } else {
          addClass(this.sliderContainer, "sliderContainer_fail");
          this.text.innerHTML = "再试一次";
          this.reset();
        }
      } else {
        addClass(this.sliderContainer, "sliderContainer_fail");
        this.fail && this.fail();
        //验证失败后，1秒后重新加载图片
        setTimeout(() => {
          this.reset();
        }, 1000);
      }
    });
  }
  // 验证
  verify() {
    const arr = this.trail; // 拖动时y轴的移动距离
    const average = arr.reduce(sum) / arr.length; // 平均值
    const deviations = arr.map((x) => x - average); // 偏差数组
    const stddev = Math.sqrt(deviations.map(square).reduce(sum) / arr.length); // 标准差
    const left = parseInt(this.block.style.left);
    return {
      spliced: Math.abs(left - this.x) < 10,
      TuringTest: average !== stddev, // 只是简单的验证拖动轨迹，相等时一般为0，表示可能非人为操作
    };
  }
  // 重置
  reset() {
    this.sliderContainer.className = "sliderContainer";
    this.slider.style.left = 0;
    this.block.style.left = 0;
    this.sliderMask.style.width = 0;
    this.clean();
    this.img.src = getRandomImg();
    this.draw();
  }
}
export default jigsaw;